import { Tabs, Badge, Spin, Popconfirm, message } from 'antd';
import classNames from 'classnames';
import { Link, useHistory, useModel } from 'umi';
import styles from './index.less';
import defaultAvatar from '@/assets/pc/images/message/detaultAvatar.png';
import { useEffect, useRef, useState } from 'react';
import Pagination from '../components/Pagination';
import { allGet } from '@/services/pc';
import Empty from '../components/Empty';
const { TabPane } = Tabs;

interface ItemProps {
  /**
   * 1 系统
   * 2 用户
   */
  role: 1 | 2;
  data: any;

  onClick: (data) => void;
}
const Item: React.FC<ItemProps> = ({ role, data = {}, onClick }) => {
  const avatar = role === 1 ? defaultAvatar : data.avatar || defaultAvatar;

  return (
    <div className={styles.item} onClick={() => onClick(data)}>
      <div className={styles.left}>
        <div className={styles.img} style={{ backgroundImage: `url(${avatar})` }} />
        {data.new == 1 && <i className={styles.dot} />}
      </div>
      <div className={styles.right}>
        <div className={styles.info}>
          <div className={styles.time}>{data?.dateline}</div>
          <div className={styles.content}>
            <div dangerouslySetInnerHTML={{ __html: data.note }}></div>
          </div>
        </div>
        {data.pic && <div className={styles.img} style={{ backgroundImage: `url(${data.pic})` }} />}
      </div>
    </div>
  );
};

const List = ({ role }) => {
  const [data, setData] = useState<any>({});

  const [loading, setLoading] = useState(true);
  const [current, setCurrent] = useState(1);
  const pageSize = 10;
  const handlePageChange = (page) => {
    setCurrent(page);
  };

  const init = async (showLoading = true) => {
    if (showLoading) {
      setLoading(true);
    }

    const response = await allGet({
      params: {
        mod: 'user',
        do: 'notice',
        version: 'pc1.0',
        op: 'list',
        ac: 'account',
        issystem: role === 1 ? 'system' : 0,
        perpage: pageSize,
        page: current,
      },
    });
    setData(response);
    setLoading(false);
  };
  useEffect(() => {
    init();
  }, [current]);
  /**
   * 消息
   */
  const { setMessageCount } = useModel('message');
  const { getUseInfo } = useModel('user');

  const handleClick = async (data) => {
    if (data.new == 0) return;
    const response = await allGet({
      params: { mod: 'user', do: 'notice', version: 'pc1.0', op: 'read', id: data.id },
    });
    if (!response.success) return;
    // 更新全局的消息数量
    getUseInfo();

    setMessageCount(0);
  };
  const handleDelete = async () => {
    const response = await allGet({
      params: {
        mod: 'user',
        do: 'notice',
        op: 'delete',
        version: 'pc1.0',
        issystem: role === 1 ? 'system' : 0,
      },
    });
    if (!response.success) {
      return;
    }
    init();
    return false;
  };
  const handleRed = async () => {
    const response = await allGet({
      params: {
        mod: 'user',
        do: 'notice',
        op: 'ignore',
        version: 'pc1.0',
        issystem: role === 1 ? 'system' : 0,
      },
    });
    if (!response.success) return;
    init(false);
    // 更新全局的消息数量
    getUseInfo();
    return false;
  };
  return (
    <>
      <div className={styles.list}>
        <div className={styles.header}>
          <div className={classNames(styles.button, styles.primary)} onClick={handleRed}>
            全部标记已读
          </div>
          <Popconfirm
            placement="left"
            title="清空后不可恢复, 确定清空?"
            onConfirm={handleDelete}
            okText="确定"
            cancelText="关闭"
          >
            <div className={styles.button}>清空消息</div>
          </Popconfirm>
        </div>
        <Spin spinning={loading}>
          {data?.data?.list?.length > 0 ? (
            data.data.list.map((item, index) => {
              return <Item key={item.id} role={role} data={item} onClick={handleClick} />;
            })
          ) : (
            <Empty />
          )}
        </Spin>
      </div>
      {data?.data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          className={styles.pagination}
          total={data?.data?.count}
          current={current}
          onChange={handlePageChange}
        />
      )}
    </>
  );
};

const Index = () => {
  const { index = 1 } = (useHistory().location as any)?.query;
  const { userInfo } = useModel('user');
  const newsystem = Number(userInfo?.newsystem || 0);
  const newhd = Number(userInfo?.['newprompt-newsystem'] || 0);
  return (
    <div className={styles.page}>
      <Tabs className="my-tabs" defaultActiveKey={index}>
        <TabPane
          tab={
            <div className={styles.tabtitle}>
              系统消息
              <Badge className={styles.badge} count={newsystem} />
            </div>
          }
          key="1"
        >
          <List role={1} />
        </TabPane>
        <TabPane
          tab={
            <div className={styles.tabtitle}>
              互动通知
              <Badge className={styles.badge} count={newhd} />
            </div>
          }
          key="2"
        >
          <List role={2} />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Index;
